<template>
  <div>
    <UserAuthorizationAllocation
      ref="UserAuthorizationAllocationRef"
      @refresh="fetchData"
    />
    <a-card class="general-card" :title="'菜单授权'">
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :bordered="false"
        :pagination="false"
      >
        <template #columns>
          <a-table-column
            title="菜单名称"
            data-index="name"
            :body-cell-style="bodyCellStyle"
          >
          </a-table-column>
          <a-table-column
            :title="$t('columns.operations')"
            align="right"
            data-index="operations"
            :width="180"
            :body-cell-style="bodyCellStyle"
          >
            <template #cell="{ record }">
              <a-button
                v-if="!record.menus"
                type="text"
                size="small"
                @click="handleClickToSave(record)"
              >
                用户授权
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import useLoading from '@/hooks/loading';
  import { TableData } from '@arco-design/web-vue';
  import tree from '@/utils/tree';
  import { Menu, selectMenuTree } from '@/api/menu';
  import UserAuthorizationAllocation from './user-authorization-allocation.vue';

  const { loading, setLoading } = useLoading();
  const renderData = ref<TableData[]>([]);
  const UserAuthorizationAllocationRef = ref();
  const bodyCellStyle = (record: any) => {
    // 判断当前行是否是子集，并据此设置背景颜色
    if (record.menus) {
      return {
        backgroundColor: 'var(--color-neutral-1)', // 子集的背景颜色
      };
    }
    return {}; // 如果不是子集，则不应用任何特殊样式
  };
  const fetchData = async () => {
    setLoading(true);
    try {
      const { data } = await selectMenuTree();
      data.forEach((item: any) => {
        item.children = item.menus
          ? tree.toTree(item.menus, 'id', 'parentId')
          : [];
      });
      renderData.value = data;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  fetchData();
  const handleClickToSave = (obj: Menu) => {
    UserAuthorizationAllocationRef.value.handleChangeVisible(obj);
  };
</script>

<script lang="ts">
  export default {
    name: 'MenuList',
  };
</script>

<style scoped lang="less">
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
